package com.djhu.aspect.log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * @author by zw on 2018/5/3.
 */
@Aspect
public class AspectLog {

    private static Logger logger = LoggerFactory.getLogger(AspectLog.class.getName());

    @Pointcut("@annotation(com.djhu.aspect.log.Logging)")
    public void pointLogging(){
    }


    @Around("pointLogging()")
    public Object log(ProceedingJoinPoint proceedingJoinPoint){
        long beginTime = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取被拦截的方法
        Method method = signature.getMethod();
        //获取被拦截的方法名
        String methodName = method.getName();
        Object[] arg = proceedingJoinPoint.getArgs();
        Logging logging = method.getAnnotation(Logging.class);
        Throwable error = null;
        Object retVal = null;
        try {
            proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            error = throwable;
        }
        long endTime = System.currentTimeMillis();
        LogProcessEntity logProcessEntity = new LogProcessEntity(methodName,beginTime,endTime,arg,retVal,error);
        logger.info("method invoke ,invoke process is {}" , logProcessEntity);
        return retVal;
    }

}